package org.ucas.kgraph.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理容器级别异常,类似web.xml中的error mapping
 * Spring Boot在应用发生错误时会转向"/error"请求，即交由BasicErrorController处理。
 *
 * @author suemi
 */
@Controller
public class ErrorController extends BasicErrorController{

  private static final Logger logger = Logger.getLogger(ErrorController.class);

  @Autowired
  public ErrorController(ServerProperties serverProperties) {
    super(new DefaultErrorAttributes(), serverProperties.getError());
  }

  /**
   * 对Accept为Json类型的请求返回符合ErrDto格式的Json返回串
   * @param request
   * @return
   */
  @Override
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request,
            isIncludeStackTrace(request, MediaType.ALL));
    HttpStatus status = getStatus(request);

    logger.error(body.toString());

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("status", status.value());
    map.put("errorCode", -1);
    map.put("message",body.get("message"));

    return new ResponseEntity<Map<String, Object>>(map, status);
  }

  /**
   * 设定一般情形下的错误页面
   * @param request
   * @param response
   * @return
   */
  @Override
  public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    return super.errorHtml(request, response); // TODO
  }
}
